import requests
from lxml import etree
import re
import webbrowser

# book_name = input('请输入你要搜索的书名：')
book_name = '史上最强赘婿'
header = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
}
res = requests.get(f'https://www.zxcs.info/index.php?keyword={book_name}',headers=header)
res.encoding = res.apparent_encoding # 防止乱码，自动转码
res_html = res.text

# 查找相关结果
tree = etree.HTML(res_html)
tree_name = tree.xpath('//div[@id="pleft"]//dt/a/text()')
print(f'搜索到的书本如下：')
for i,k in enumerate(tree_name):
    print(f'{i+1} {k}')

# book_download = int(input('请输入你要下载哪本书（直接填序号）:'))

# tree_address = tree.xpath('//div[@id="pleft"]//dt/a/@href')[book_download-1]
tree_address = tree.xpath('//div[@id="pleft"]//dt/a/@href')[0]

# 点击“下载小说”
res_2 = requests.get(url=tree_address,headers=header)
res_2.encoding = res_2.apparent_encoding # 防止乱码，自动转码
res2_html = res_2.text

tree = etree.HTML(res2_html)
tree_main_url = tree_address.replace(tree_address.split('.')[-1],tree_address.split('//')[-1].split('.')[-1].split('/')[0])
tree_address_2 = tree.xpath('//div[@class="fans-interact cf"]/a/@href')
tree_address_new = tree_main_url + ''.join(tree_address_2)
print(f'最终得到的链接：{tree_address_new}')

# 获取网盘下载链接及提取码
res_3 = requests.get(url=tree_address_new,headers=header).text
tree = etree.HTML(res_3)
tree_address_finally = tree.xpath('//span[@class="downfile"]/a/@href')
tree_text_finally = tree.xpath('//span[@class="downfile"]/a/text()')
tree_local_download = tree.xpath('//a[@class="localdown"]/@href')
if tree_local_download:
    print('存在本地下载！')
    local_download_host_re = re.findall('var url=(.*?);\n', res_3, re.S)
    local_download_host_1 = ''.join(local_download_host_re).replace('"', '')
    local_download_host = tree_main_url
    local_download_url_re = re.findall('url:(.*?),\n', res_3, re.S)
    local_download_url = ''.join(local_download_url_re).strip().replace("'", '')
    local_download_url_finally = local_download_host + local_download_url
    print(local_download_url_finally)
    local_download_data_re = re.findall('data:(.*?),\n', res_3, re.S)[0].strip()
    local_download_data = re.findall('{(.*):(.*)}',local_download_data_re)
    print(local_download_data)
    res = requests.post(url=local_download_url_finally,headers=header,data=local_download_data).text
    print(res)
    local_download_url_href = local_download_host_1 + res
    print(local_download_url_href)
    webbrowser.open(local_download_url_href)

if not tree_address_finally:
    print('找不到下载入口！原因：网盘链接丢失！')
else:
    print(f'网盘链接：{tree_address_finally[0]} {tree_text_finally[0]}')
